const verificatF = require('./verificat_first.js');
const verificatS = require('./verificat_second.js');
const calculate = require('./calculate.js');
const rl = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
})

// 验证输入的信源概率分布
const verification = (args) => {
  let sum = 0
  args.forEach(arg => {
    sum = +arg + sum
  })
  // 验证输入的信源概率分布
  const newargs = verificatF(sum, args)
  if (newargs) {
    // 如果输入的概率和为1，则返回信源概率分布
    return newargs
  } else {
    // 如果输入的概率和不为1或其他错误输入，则提示用户继续输入
    console.log('请输入信源概率分布：(Ctrl+D 退出输入)');
    args = []
    let num = 0

    const checkTotal = () => {
      return new Promise((resolve, reject) => {
        const askForInput = () => {
          let total = 0
          args.forEach(arg => { total = arg + total })
          // 如果概率和为1，则返回信源概率分布
          if (total === 1) {
            resolve(args)
            return args
          }
          // 如果概率和大于1，则提示用户重新输入
          if (total > 1) {
            console.log('概率和不为1，请重新输入！')
            args = []
            num = 0
            askForInput()
          }
          // 如果概率和小于1，则继续输入
          rl.question(`p${num}:`, input => {
            const data = +input
            // 验证输入的信源概率分布
            const newinput = verificatS(data)
            if (newinput) {
              args.push(newinput)
              num++
              askForInput()
            } else {
              askForInput()
            }
          })
        }
        askForInput()
      })
    }
    checkTotal().then(newargs => {
      // 计算信源的熵
      calculate(newargs)
    })
  }
}

module.exports = verification;